//
//  StringSample.swift
//  SampleCommandLineTool
//
//  Created on 10/12/23.
//

import Foundation

func printStringDetail(_ str: String) {
    var detail = ""
    detail += "String: \(str), "
    detail += "String length: \(str.count), "
    detail += "NSString length: \((str as NSString).length), "
    detail += "\n"
    detail += "UTF-8, \(utfDetail(str.utf8))\n"
    detail += "UTF-16, \(utfDetail(str.utf16))\n"
    detail += "UTF-32, \(utfDetail(str.unicodeScalars))\n"
    print(detail)
    let a = detail[detail.startIndex]
    
}

func utfDetail(_ utf: any Collection) -> String {
    var detail = ""
    switch utf {
    case is String.UTF8View:
        detail += "byte count: \(utf.count), bytes: "
    case is String.UTF16View:
        detail += "byte count: \(utf.count * 2), bytes: "
    case is String.UnicodeScalarView:
        detail += "byte count: \(utf.count * 4), bytes: "
    default:
        detail += "code units: "
    }
    for codeUnit in utf {
        switch codeUnit {
        case let codeUnit as UInt8:
            detail += "\(codeUnit)(0x\(String(format: "%02x", codeUnit).uppercased())) "
        case let codeUnit as UInt16:
            detail += "\(codeUnit)(0x\(String(format: "%04x", codeUnit).uppercased())) "
        case let codeUnit as UnicodeScalar:
            detail += "\(codeUnit.value)(0x\(String(format: "%08x", codeUnit.value).uppercased())) "
        default:
            detail += "\(codeUnit)"
        }
    }
    return detail
}


func runStringLengthSample() {
    printStringDetail("a");
    printStringDetail("α");
    printStringDetail("中");
    printStringDetail("😀");
    printStringDetail("\u{65}");
    printStringDetail("\u{301}");
    printStringDetail("\u{65}" + "\u{301}");
    printStringDetail("\u{E9}")
    printStringDetail("Dog‼🐶")
}
